package cn.eric.framework.log.log4j2;

import org.apache.logging.log4j.core.config.Configurator;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Enumeration;

/**
 * 用于实现自定义的log4j2的配置文件和文件名
 */
public class Log4j2ConfigListener implements ServletContextListener {
    private static final String CONFIG_PATH_KEY = "log4j2.config.path";
    private static final String LOG4J2 = "Log4j2";

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        String path = getContextParam(servletContextEvent);
        Configurator.initialize(LOG4J2, path);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    private String getContextParam(ServletContextEvent event) {
        Enumeration<String> names = event.getServletContext().getInitParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = event.getServletContext().getInitParameter(name);
            if (name.trim().equals(CONFIG_PATH_KEY)) {
                return value;
            }
        }
        return null;
    }
}
